from fastapi import FastAPI, HTTPException, status, Depends
from pydantic import BaseModel
from typing import Optional, List



# 创建 FastAPI 应用实例
app = FastAPI(debug=True)

# 内存数据库（临时存储用户数据）
users_db = []


# 用户数据模型
class User(BaseModel):
    id: Optional[int] = None
    name: str
    email: str
    age: Optional[int] = None


# 根路由
@app.get("/")
def read_root():
    return {"message": "欢迎使用用户管理API"}


# 创建用户
@app.post("/users/", response_model=User, status_code=status.HTTP_201_CREATED)
def create_user(user: User):
    """创建新用户"""
    # 分配用户ID
    user.id = len(users_db) + 1
    users_db.append(user.model_dump())
    return user


# 获取所有用户
@app.get("/users/", response_model=List[User])
def get_all_users():
    """获取所有用户列表"""
    return users_db


# 获取单个用户
@app.get("/users/{user_id}", response_model=User)
def get_user(user_id: int):
    """通过ID获取用户"""
    for user in users_db:
        if user["id"] == user_id:
            return user
    raise HTTPException(status_code=404, detail="用户不存在")


# 更新用户信息
@app.put("/users/{user_id}", response_model=User)
def update_user(user_id: int, updated_user: User):
    """更新用户信息"""
    for idx, user in enumerate(users_db):
        if user["id"] == user_id:
            # 保留ID不变
            updated_user.id = user_id
            users_db[idx] = updated_user.model_dump()
            return updated_user
    raise HTTPException(status_code=404, detail="用户不存在")


# 删除用户
@app.delete("/users/{user_id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_user(user_id: int):
    """删除用户"""
    global users_db
    original_count = len(users_db)
    users_db = [user for user in users_db if user["id"] != user_id]

    if len(users_db) == original_count:
        raise HTTPException(status_code=404, detail="用户不存在")
    return  # 204响应无内容


if __name__ == '__main__':
    import uvicorn
    uvicorn.run("main:app", host="127.0.0.1", port=8000, reload=True)